import frappe
from frappe import _
from frappe.utils import add_days, now_datetime
from link_history.utils.link_history import batch_update_history, CACHE_PREFIX

def daily():
    """每日任务：清理旧的历史记录"""
    try:
        # 删除 30 天前的历史记录
        cutoff_date = add_days(now_datetime(), -30)
        
        # 删除旧记录
        frappe.db.sql("""
            DELETE FROM `tabLink History Record` 
            WHERE last_used < %s
        """, (cutoff_date,))
        
        # 删除无效记录
        frappe.db.sql("""
            DELETE FROM `tabLink History Record` 
            WHERE link_name IS NULL OR link_name = '' OR link_name = 'undefined'
            OR link_title IS NULL OR link_title = '' OR link_title = 'undefined'
        """)
        
        # 清除缓存
        frappe.cache.delete_key(CACHE_PREFIX)
        
        frappe.db.commit()
        
        # 记录日志
        frappe.logger().info("Link History 每日清理任务完成")
    except Exception as e:
        frappe.log_error(f"清理历史记录时出错: {e}", "Link History Daily Task") 

def hourly():
    """每小时任务"""
    try:
        # 记录开始执行
        frappe.logger().info("开始执行 Link History 每小时任务")
        
        # 执行每小时任务，例如批量更新历史记录
        batch_update_history()
        
        # 记录完成执行
        frappe.logger().info("Link History 每小时任务完成")
    except Exception as e:
        frappe.log_error(f"执行每小时任务时出错: {e}", "Link History Hourly Task") 